package ee.greaton.siteManager.FTP;

import java.io.IOException;
import java.net.SocketException;
import java.util.ArrayList;

import javax.swing.tree.DefaultMutableTreeNode;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import ee.greaton.siteManager.model.Site;

public class FTPmanager {

	Site site;
	FTPClient ftpClient;

	public FTPmanager(Site site) {
		this.site = site;
		ftpClient = new FTPClient();
		try {
			// pass directory path on server to connect
			ftpClient.connect(site.getFtpUrl());

			boolean login = ftpClient.login(site.getFtpUser(),
					site.getFtpPass());

			if (login) {
				System.out.println("Connection established...");
				System.out.println("Status: " + ftpClient.getStatus());
			} else {
				System.out.println("Connection fail...");
			}

		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
		}
	}

	public void close() {
		try {
			boolean logout = ftpClient.logout();
			if (logout) {
				System.out.println("Connection close...");
			} else {
				System.out.println("Connection close failed...");
			}
			ftpClient.disconnect();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public DefaultMutableTreeNode getRootDirectoryTree() {
		DefaultMutableTreeNode root = null;
		
		try {
			FTPFile[] list = ftpClient.listDirectories();
			root = new DefaultMutableTreeNode("Root");
			if(list.length > 0){
				for (FTPFile f : list) {
					if(!f.getName().equals(".") && !f.getName().equals("..")){
						root.add(new DefaultMutableTreeNode(f.getName()));
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return root;
	}
	public ArrayList<DefaultMutableTreeNode> getDirectoryTree(String dir, String name) {
		ArrayList<DefaultMutableTreeNode> root = new ArrayList<DefaultMutableTreeNode>();
		try {
			FTPFile[] list;
			list = ftpClient.listDirectories(dir);
			if(list.length > 0){
				for (FTPFile f : list) {
					if(!f.getName().equals(".") && !f.getName().equals("..")){
						root.add(new DefaultMutableTreeNode(f.getName()));
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return root;
	}
}
